package cn.edu.stu.syllabus.library.detail;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.edu.stu.syllabus.R;
import cn.edu.stu.syllabus.adapters.BookLocateAdapter;
import cn.edu.stu.syllabus.adapters.InformationAdapter;
import cn.edu.stu.syllabus.base.BaseFragment;
import cn.edu.stu.syllabus.base.StoreProxy;
import cn.edu.stu.syllabus.datas.Information;
import cn.edu.stu.syllabus.repository.booklocate.local.BookLocateEntry;
import cn.edu.stu.syllabus.utils.DensityUtil;
import cn.edu.stu.syllabus.widgets.DividerItemDecoration;
import cn.edu.stu.syllabus.widgets.NestedScrollViewScrollAdapter;
import cn.edu.stu.syllabus.widgets.ScrollEnabledLinearLayoutManager;

import static cn.edu.stu.syllabus.utils.NullPointerUtils.checkNotNull;

/**
 * Created by daidaijie on 2017/3/28.
 */

public class BookDetailFragment extends BaseFragment implements BookDetailContract.View, BookDetailActivity.OnStarButtonStateChangeListener {

    @BindView(R.id.bookDetailWebView)
    WebView mBookDetailWebView;
    @BindView(R.id.bookInformationRecyclerView)
    RecyclerView mBookInformationRecyclerView;
    @BindView(R.id.bookInformationCardView)
    CardView mBookInformationCardView;
    @BindView(R.id.bookLocateRecyclerView)
    RecyclerView mBookLocateRecyclerView;
    @BindView(R.id.bookLocateCardView)
    CardView mBookLocateCardView;
    @BindView(R.id.bookLocateInformationHeadView)
    View mBookLocateInformationHeadView;
    @BindView(R.id.bookLocateEmptyView)
    View mBookLocateEmptyView;
    @BindView(R.id.bookLocateErrorView)
    View mBookLocateErrorView;
    @BindView(R.id.bookDetailRootLayout)
    NestedScrollView mBookDetailRootLayout;

    private InformationAdapter mInformationAdapter;

    private BookLocateAdapter mBookLocateAdapter;

    private BookDetailContract.Presenter mPresenter;

    View mBookInformationHeadView;

    View mLocateTableHeadView;

    public static BookDetailFragment newInstance() {
        BookDetailFragment bookDetailFragment = new BookDetailFragment();
        return bookDetailFragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_book_detail;
    }

    @Override
    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    protected void init(Bundle savedInstanceState) {

        WebSettings settings = mBookDetailWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        mBookDetailWebView.addJavascriptInterface(new InJavaScriptLocalObj(), "local_obj");
        mBookDetailWebView.setWebViewClient(new MyWebViewClient());

        mBookLocateAdapter = new BookLocateAdapter(new ArrayList<BookLocateEntry>());
        mBookLocateRecyclerView.setLayoutManager(new ScrollEnabledLinearLayoutManager(mActivity, false));
        mBookLocateRecyclerView.setAdapter(mBookLocateAdapter);
        Drawable decLineDrawable = ContextCompat.getDrawable(mActivity, R.drawable.dev_line_full);
        DividerItemDecoration itemDecoration = new DividerItemDecoration(
                mActivity, DividerItemDecoration.VERTICAL_LIST, decLineDrawable);
        itemDecoration.setHeight(DensityUtil.dip2px(1f));
        mBookLocateRecyclerView.addItemDecoration(itemDecoration);

        ViewCompat.setNestedScrollingEnabled(mBookLocateRecyclerView, false);

        TextView informationHeadTextView = (TextView) mBookLocateInformationHeadView.findViewById(R.id.informationHeadTextView);
        informationHeadTextView.setText("借阅信息");
        Drawable inFormationDrawable = ContextCompat.getDrawable(mActivity, R.drawable.ic_information);
        informationHeadTextView.setCompoundDrawablesWithIntrinsicBounds(inFormationDrawable, null, null, null);


        View divLine = LayoutInflater.from(mActivity).inflate(
                R.layout.dev_line_hor, (ViewGroup) mBookInformationRecyclerView.getParent(), false
        );
        mBookLocateAdapter.addHeaderView(divLine, 0);

        mLocateTableHeadView = LayoutInflater.from(mActivity).inflate(
                R.layout.item_book_locate, (ViewGroup) mBookInformationRecyclerView.getParent(), false
        );
        TextView mLocateNameTextView = (TextView) mLocateTableHeadView.findViewById(R.id.locateNameTextView);
        TextView mLocateStateTextView = (TextView) mLocateTableHeadView.findViewById(R.id.locateStateTextView);
        TextView mLocateTypeTextView = (TextView) mLocateTableHeadView.findViewById(R.id.locateTypeTextView);
        mLocateTableHeadView.setBackgroundColor(ContextCompat.getColor(mActivity, R.color.colorCardPress));
        mLocateNameTextView.setText(Html.fromHtml("<b>馆藏地</b>"));
        mLocateStateTextView.setText(Html.fromHtml("<b>状态</b>"));
        mLocateTypeTextView.setText(Html.fromHtml("<b>借阅类型</b>"));

        mBookLocateAdapter.addHeaderView(mLocateTableHeadView, 1);

        mBookLocateErrorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Logger.e("onClick");
                mPresenter.loadBookLocates();
            }
        });

        mBookDetailRootLayout.setOnScrollChangeListener(new NestedScrollViewScrollAdapter() {
            @Override
            public void onScrollToBottom() {
                mBookDetailRootLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showAppBar();
                    }
                }, 50);
            }
        });

        StoreProxy.onRestoreInstanceState(savedInstanceState, mPresenter);
        mPresenter.subscribe();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        StoreProxy.onSaveInstanceState(outState, mPresenter);
    }

    @Override
    public void setPresenter(BookDetailContract.Presenter presenter) {
        mPresenter = checkNotNull(presenter);
    }

    @Override
    public void loadUrl(String url) {
        mBookDetailWebView.loadUrl(url);
    }

    @Override
    public void showInformation(List<Information> informations) {
        mBookInformationHeadView = LayoutInflater.from(mActivity).inflate(
                R.layout.head_information, (ViewGroup) mBookInformationRecyclerView.getParent(), false
        );
        TextView informationHeadTextView = (TextView) mBookInformationHeadView.findViewById(R.id.informationHeadTextView);
        informationHeadTextView.setText("书籍信息");
        Drawable inFormationDrawable = ContextCompat.getDrawable(mActivity, R.drawable.ic_information);
        informationHeadTextView.setCompoundDrawablesWithIntrinsicBounds(inFormationDrawable, null, null, null);
        mInformationAdapter = new InformationAdapter(informations, 4);
        mInformationAdapter.addHeaderView(mBookInformationHeadView);
        mBookInformationRecyclerView.setLayoutManager(new ScrollEnabledLinearLayoutManager(mActivity, false));
        mBookInformationRecyclerView.setAdapter(mInformationAdapter);
        ViewCompat.setNestedScrollingEnabled(mBookInformationRecyclerView, false);
    }

    @Override
    public void showBookLocate(List<BookLocateEntry> bookLocateEntries) {
        mBookLocateAdapter.setNewData(bookLocateEntries);
        mBookLocateRecyclerView.setVisibility(View.VISIBLE);
        mBookLocateEmptyView.setVisibility(View.GONE);
        mBookLocateErrorView.setVisibility(View.GONE);
    }

    @Override
    public void showLoading() {
        mBookLocateEmptyView.setAlpha(1.0f);
        mBookLocateErrorView.setAlpha(0.0f);
        mBookLocateErrorView.setClickable(false);
    }

    @Override
    public void showError() {
        mBookLocateErrorView.setAlpha(1.0f);
        mBookLocateEmptyView.setAlpha(0.0f);
        mBookLocateErrorView.setClickable(true);
    }

    @Override
    public void onDestroyView() {
        mPresenter.unsubscribe();
        super.onDestroyView();
    }

    @Override
    public boolean isStar() {
        return mPresenter.isStarBook();
    }

    @Override
    public void onStateChange(boolean isStar) {
        if (isStar) {
            mPresenter.starBook();
        } else {
            mPresenter.unstarBook();
        }
    }

    private final class MyWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            view.loadUrl(request.getUrl().toString());
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d("HTML", "onPageStarted: ");
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(final WebView view, String url) {
            view.postDelayed(new Runnable() {
                @Override
                public void run() {
                    view.loadUrl("javascript:window.local_obj.showSource('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
                }
            }, 2000);
            super.onPageFinished(view, url);
        }
    }

    private final class InJavaScriptLocalObj {
        @JavascriptInterface
        public void showSource(String html) {
            mPresenter.parseHtml(html);
        }
    }
}
